#define _CRT_SECURE_NO_WARNINGS	1
#include "stack.h"
void STInit(ST* pst) {
	assert(pst);
	pst->val = NULL;
	pst->top = -1;
	pst->capacity = 0;
}
void STPush(ST* pst, STtypedate x) {
	assert(pst);
	if (pst->top + 1 == pst->capacity)
	{
		int newcapacity = pst->capacity == NULL ? 4 : pst->capacity * 2;
		STtypedate* temp = (STtypedate*)realloc(pst->val, sizeof(STtypedate) * newcapacity);
		if (temp == NULL)
		{
			perror("realloc:");
			return;
		}
		pst->val = temp;
		pst->capacity = newcapacity;
	}
	pst->top++;
	pst->val[pst->top] = x;
}
void STPop(ST* pst) {
	assert(pst);
	assert(pst->top >= 0);
	pst->top--;
}
STtypedate STTop(ST* pst) {
	assert(pst);
	assert(pst->top >= 0);
	return pst->val[pst->top];
}
int STSize(ST* pst) {
	assert(pst);
	return pst->top + 1;
}
int STEmpty(ST* pst) {
	assert(pst);
	if (pst->top == -1)
		return -1;
	else 
		return 0;
}
void STPrint(ST pst) {
	for (int n = 0; n <= pst.top; n++)
	{
		printf("%d<=", pst.val[n]);
	}
	printf("\n");
}
void STDistory(ST* pst) {
	assert(pst);
	free(pst->val);
	pst->val = NULL;
	pst->top = -1;
	pst->capacity = 0;
}

MyQueue* myQueueCreate() {
    MyQueue* newnode = (MyQueue*)malloc(sizeof(MyQueue));
    STInit(&newnode->q1);
    STInit(&newnode->q2);
    return newnode;
}

void myQueuePush(MyQueue* obj, int x) {
    if (!STEmpty(&obj->q1))
    {
        STPush(&obj->q1, x);
    }
    else {
        STPush(&obj->q2, x);
    }
}

int myQueuePop(MyQueue* obj) {
    ST* empty = &obj->q1;
    ST* noempty = &obj->q2;
    if (!STEmpty(empty))
    {
        empty = &obj->q2;
        noempty = &obj->q1;
    }
    while (STSize(noempty) > 1)
    {
        STPush(empty, STTop(noempty));
        STPop(noempty);
    }
    int cur = STTop(noempty);
    STPop(noempty);
    while (STSize(empty) >= 1)
    {
        STPush(noempty, STTop(empty));
        STPop(empty);
    }
    return cur;
}

int myQueuePeek(MyQueue* obj) {
    ST* empty = &obj->q1;
    ST* noempty = &obj->q2;
    if (!STEmpty(empty))
    {
        empty = &obj->q2;
        noempty = &obj->q1;
    }
    while (STSize(noempty) > 1)
    {
        STPush(empty, STTop(noempty));
        STPop(noempty);
    }
    int cur = STTop(noempty);
    STPush(empty, STTop(noempty));
    STPop(noempty);
    while (STSize(empty) >= 1)
    {
        STPush(noempty, STTop(empty));
        STPop(empty);
    }
    return cur;
}

bool myQueueEmpty(MyQueue* obj) {
    return STEmpty(&obj->q1) && STEmpty(&obj->q2);
}

void myQueueFree(MyQueue* obj) {
    STDistory(&obj->q1);
    STDistory(&obj->q2);
    free(obj);
}